package org.ffsky.jsplugin.plugin;


import com.alibaba.fastjson.JSONObject;
import com.ffsky.litepack.Lite;
import com.ffsky.litepack.util.StringCompat;
import ohos.agp.components.webengine.JsCallback;
import ohos.agp.components.webengine.WebView;
import org.ffsky.jsplugin.JsPlugin;

public class CacheJsPlugin extends JsPlugin {

    private final String EXT_KEY = "_H5_";
    @Override
    public void bindJsBridge(WebView webView) {
        webView.addJsCallback("cache.save", new JsCallback() {
            @Override
            public String onCallback(String jsonArgs) {
                JSONObject json = JSONObject.parseObject(jsonArgs);
                if(json.containsKey("key") && json.containsKey("value")){
                    String key = json.getString("key");
                    String value = json.getString("value");
                    Lite.cache.save(StringCompat.string(EXT_KEY,key), value);
                    return JsPlugin.RESULT_OK;
                }
                return null;
            }
        });

        webView.addJsCallback("cache.read", new JsCallback() {
            @Override
            public String onCallback(String jsonArgs) {
                JSONObject json = JSONObject.parseObject(jsonArgs);
                if(json.containsKey("key") ){
                    String key = json.getString("key");
                    String value = Lite.cache.read(StringCompat.string(EXT_KEY,key));
                    return value;
                }
                return null;
            }
        });

        webView.addJsCallback("cache.del", new JsCallback() {
            @Override
            public String onCallback(String jsonArgs) {
                JSONObject json = JSONObject.parseObject(jsonArgs);
                if(json.containsKey("key") ){
                    String key = json.getString("key");
                    Lite.cache.del(StringCompat.string(EXT_KEY,key));
                    return JsPlugin.RESULT_OK;
                }
                return null;
            }
        });
    }
}
